<?php

class wxpay_app {
    public function __construct($payment_info = array())
    {
        define('WXN_APPID', $payment_info['payment_config']['wx_appid']);
        define('WXN_APPSECRET', $payment_info['payment_config']['wx_appsecret']);
        define('WXN_MCHID', $payment_info['payment_config']['wx_mch_id']);
        define('WXN_KEY', $payment_info['payment_config']['wx_key']);
    }
    function get_payform($param=array()) {

        define("APPID", WXN_APPID);
        define("MCHID", WXN_MCHID);
        define("KEY", WXN_KEY);


        require_once PLUGINS_PATH . '/payments/wxpay_native/lib/WxPay.Api.php';
        //统一下单  nonce_str、sign、spbill_create_ip  在接口调用统一设置
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($param['subject']);
        $input->SetAttach($param['order_type']);
	    $input->SetOut_trade_no($param['pay_sn'].'_'.TIMESTAMP);
        //$input->SetOut_trade_no($param['order_type'].'-'.$param['pay_sn']);
        $input->SetTotal_fee(bcmul($param['api_pay_amount'] , 100));
        $input->SetNotify_url(str_replace('/index.php', '', HOME_SITE_URL) . '/payment/wxpay_app_notify.html');
        $input->SetTrade_type('APP');

        $wxpay = new \WxPayApi();
        $order = $wxpay->unifiedOrder($input);
        \think\Log::error("微信参数:".json_encode($order));
        if (is_array($order) && $order['return_code'] == 'SUCCESS') {
            if ($order['result_code'] == 'SUCCESS') {
            	$options=$this->appParams($order['prepay_id']);
	            \think\Log::error("微信参数1122:".json_encode($options));
	            $options['package_value']=$options['package'];
	            $options['mch_id']=$options['partnerid'];
	            //$options['partnerid']=$options['partnerid'];
	            $options['prepay_id']=$options['prepayid'];
	            $options['nonce_str']=$options['noncestr'];
	            unset($options['package']);
                //$order['timestamp'] = time();
                //$order['nonce_str'] = WxPayApi::getNonceStr();
                //$order['sign'] = $this->sign_again($order);

                ds_json_encode(10000,'',array('content'=> json_encode($options),'content_android'=> $options));
            } else {
                ds_json_encode(10001,$order['err_code_des']);
            }
        } else {
            ds_json_encode(10001,$order['return_msg']);
        }
    }

    function sign_again($order) {
        $values['appid'] = WXN_APPID;
        $values['partnerid'] = WXN_MCHID;
        $values['prepayid'] = $order['prepay_id'];
        $values['package'] = 'Sign=WXpay';
        $values['noncestr'] = $order['nonce_str'];
        $values['timestamp'] = $order['timestamp'];
        
        ksort($values);
        $buff = "";
        foreach ($values as $key => $value) {
            $buff .= $key . "=" . $value . "&";
        }

        $string = trim($buff, "&");
        $string = $string . "&key=" . KEY;
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }


	/**
	 * 获取微信App支付秘需参数
	 * @param string $prepayId 统一下单预支付码
	 * @return array
	 */
	public function appParams($prepayId)
	{
		$data = [
			'appid'     => WXN_APPID,
			'partnerid' => WXN_MCHID,
			'prepayid'  => (string)$prepayId,
			'package'   => 'Sign=WXPay',
			'timestamp' => (string)time(),
			'noncestr'  => WxPayApi::getNonceStr(),
		];
		$data['sign'] = $this->getPaySign($data, 'MD5');
		return $data;
	}

		/**
	 * 生成支付签名
	 * @param array $data 参与签名的数据
	 * @param string $signType 参与签名的类型
	 * @param string $buff 参与签名字符串前缀
	 * @return string
	 */
	public function getPaySign(array $data, $signType = 'MD5', $buff = '')
	{
		ksort($data);
		if (isset($data['sign'])) unset($data['sign']);
		foreach ($data as $k => $v) $buff .= "{$k}={$v}&";
		$buff .= ("key=" . KEY);
		if (strtoupper($signType) === 'MD5') {
			return strtoupper(md5($buff));
		}
		return strtoupper(hash_hmac('SHA256', $buff, KEY));
	}

}
